package com.example.filter;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Create with Intellij idea
 * User:鲁智明
 * Date:2018/11/22
 * Time:23:37
 */
@Component
public class ZuulFilter extends com.netflix.zuul.ZuulFilter {

    //过滤类型pre 表示在请求之前进行
    @Override
    public String filterType() {
        return "pre";
    }

    //过滤器执行顺序  当一个请求在同一个阶段的时候存在多个过滤器时，多个过滤器的执行顺序
    @Override
    public int filterOrder() {
        return 0;
    }

    //表示过滤器是否生效
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //编写过滤器的业务逻辑方法
    @Override
    public Object run() throws ZuulException {
        //1.获取上下文信息
        RequestContext requestContext = RequestContext.getCurrentContext();
        //2.获取request
        HttpServletRequest request = requestContext.getRequest();
        //3.获取token 从请求头中获取
        String userToken=request.getParameter("userToken");
        if(StringUtils.isEmpty(userToken)){
            //不会继续往下执行  不会再去调用服务接口，网管直接响应客户端
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseBody("userToken is null");
            requestContext.setResponseStatusCode(401);
            //返回一个提示
            return null;
        }
        //正常执行  调用其他接口
        return null;
    }
}
